import { Request, Response, NextFunction } from 'express'

export const requestUrl = (req: Request, res: Response, next: NextFunction) => {
  console.log('url:' + req.url)
  next()
}

export const defaultErrorHandler = (
  err: any,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  let statusCode: number, message: string

  switch (err.message) {
    case 'USER_NAME_OR_PASSWORD_IS_EMPTY':
      statusCode = 400
      message = '用户名或密码不能为空'
      break
    case 'PASSWORD_IS_REQUIRED':
      statusCode = 400
      message = '密码不能为空'
      break
    case 'PASSWORD_IS_INCORRECT':
      statusCode = 400
      message = '密码不正确'
      break
    case 'PASSWORD_IS_THE_SAME':
      statusCode = 400
      message = '新密码不能和旧密码相同'
      break
    case 'USER_ALREADY_EXISTS':
      statusCode = 409
      message = '该用户已存在'
      break
    case 'USER_NOT_FOUND':
      statusCode = 409
      message = '该用户不存在'
      break
    case 'USER_LOGIN':
      statusCode = 400
      message = '用户名或密码错误'
      break
    case 'UNAUTHENTICATED':
      statusCode = 401
      message = '用户未登录'
      break
    case 'UNPERMISSTION':
      statusCode = 403
      message = '用户未授权'
      break
    case 'FILE_NOT_FOUND':
      statusCode = 404
      message = '文件不存在'
      break
    case 'TAG_ALREADY_EXISTS':
      statusCode = 400
      message = '标签已存在'
      break
    case 'UNABLE_TO_REPLY_TO_REPLY':
      statusCode = 400
      message = '不能回复评论的回复'
      break
    case 'NOT_FOUND':
      statusCode = 404
      message = '文章不存在'
      break
    default:
      statusCode = 500
      message = err.message
      break
  }

  res.status(statusCode).json({ message })
}
